# -*- coding: UTF-8 -*-
from typing import Dict, Union, List

from tortoise import fields
from tortoise.models import Model

from dispatcher.common_utils.clutter_utils import string_format


class DataBlockModel(Model):
    id = fields.IntField(pk=True)

    def __str__(self):
        return f'<{self.__class__.__name__} {self.id}>'

    @classmethod
    def to_dict(cls, ):
        # todo
        return {}

    class Meta:
        app = 'admin'
        table = 'shield_task'


class DataBlockModelManager(object):
    @classmethod
    async def insert_or_update_data_block(cls, data: Union[List[Dict], Dict]):
        data_list = data if isinstance(data, list) else [data]
        fields = [string_format(list(data.values())) for data in data_list]
        keys = list(data_list[0].keys())
        sql = f"""
            INSERT INTO data_block ({string_format(keys)}) VALUES {string_format(fields)} 
            ON DUPLICATE KEY UPDATE block_sn=values(block_sn)
"""
        # fixme 缺了执行方法


    @classmethod
    async def insert_data_block(cls, data: Union[List[Dict], Dict]):
        # todo 这里以后可能会做读写分离
        if isinstance(data, Dict):
            await DataBlockModel.create(**data)
        data_block_object = [DataBlockModel(**obj) for obj in data]
        return await DataBlockModel.bulk_create(data_block_object)

    @classmethod
    async def update_data_block(cls, where: Dict, data: Dict):
        return await DataBlockModel.filter(**where).update(**data)

    @classmethod
    async def query_expires_soon_tasks(cls, where: Dict, limit: int):
        return await DataBlockModel.filter(**where).limit(limit)

